package com.mtgdeckbuilder.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.mtgdeckbuilder.client.DeckService;
import com.mtgdeckbuilder.server.dao.CardDAO;
import com.mtgdeckbuilder.server.dao.DeckDAO;
import com.mtgdeckbuilder.server.entity.Card;
import com.mtgdeckbuilder.server.entity.Deck;
import com.mtgdeckbuilder.server.transformer.CardTransformer;
import com.mtgdeckbuilder.server.transformer.DeckTransformer;
import com.mtgdeckbuilder.shared.dto.CardDTO;
import com.mtgdeckbuilder.shared.dto.DeckDTO;

/**
 * The server side implementation of the RPC service.
 * 
 * @author Nicolas Deslandes
 */
@SuppressWarnings("serial")
public class DeckServiceImpl extends RemoteServiceServlet implements DeckService {

   private static Logger logger = Logger.getLogger(CardServiceImpl.class.getName());

   private static final DeckDAO deckDao = new DeckDAO();
   private static final CardDAO cardDao = new CardDAO();

   @Override
   public DeckDTO fetch(final long id) throws IOException {
      logger.finest("Call of fetch(" + id + ")");
      return DeckTransformer.entityToDto(deckDao.fetch(id));
   }

   @Override
   public List<DeckDTO> query(final DeckDTO args) throws IOException {
      logger.finest("Call of query(" + args + ")");
      final List<Deck> entitys = deckDao.query(DeckTransformer.dtoToEntity(args));
      final List<DeckDTO> dtos = new ArrayList<DeckDTO>();
      for (final Deck entity : entitys) {
         final DeckDTO dto = DeckTransformer.entityToDto(entity);
         for (final Key key : entity.getCards()) {
            final Card card = cardDao.fetch(key);
            final CardDTO cardDTO = CardTransformer.entityToDto(card);
            dto.getCards().add(cardDTO);
         }
         dtos.add(dto);
      }
      return dtos;
   }

   @Override
   public void save(final DeckDTO deckDto) {
      logger.finest("Call of save(" + deckDto + ")");
      final Deck deck = DeckTransformer.dtoToEntity(deckDto);
      for (final CardDTO cardDto : deckDto.getCards()) {
         final Card card = CardTransformer.dtoToEntity(cardDto);
         card.setKey(KeyFactory.createKey(Card.class.getSimpleName(), cardDto.getMultiverseId()));
         cardDao.save(card);
         deck.getCards().add(card.getKey());
      }
      deckDao.save(deck);
   }

}
